package us.wili.dev.common.util.sms.alidayu;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import us.wili.dev.common.util.sms.AliyunSmsExpcetion;
import us.wili.dev.common.util.sms.AliyunErrorCodeEnum;

/**
 * 废弃，请使用阿里云短信
 * <p>
 * Created by JasonY on 17/6/5.
 */
@Deprecated
public class AlidayuSmsUtil {

    private AlidayuProperties properties;
    private TaobaoClient client;

    public AlidayuSmsUtil() {
    }

    public AlidayuSmsUtil(AlidayuProperties properties) {
        this.properties = properties;
        this.client = new DefaultTaobaoClient(properties.getUrl(), properties.getAppkey(), properties.getSecretkey());
    }

    public AlidayuSmsUtil(String url, String appkey, String secretkey, String signName, String templateCode) {
        properties = new AlidayuProperties(url, appkey, secretkey, signName, templateCode);
        this.client = new DefaultTaobaoClient(properties.getUrl(), properties.getAppkey(), properties.getSecretkey());
    }

    public void sendNormalSms(String phone, String templateCode, String content) {
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName(properties.getSignName());
        req.setSmsTemplateCode(templateCode);
        req.setSmsParamString(content);
        req.setRecNum(phone);

        try {
            AlibabaAliqinFcSmsNumSendResponse response = client.execute(req);

            if (!response.isSuccess()) {
                AliyunErrorCodeEnum errorCodeEnum = AliyunErrorCodeEnum.get(response.getSubCode());
                throw new AliyunSmsExpcetion(errorCodeEnum.getMsg());
            }
        } catch (ApiException e) {
            throw new AliyunSmsExpcetion(AliyunErrorCodeEnum.DEFAULT_EXCEPTION.getMsg());
        }
    }

    public void sendNormalSms(String phone, String content) {
        if (properties.getTemplateCode() == null) {
            throw new AliyunSmsExpcetion("templateCode can not bu null");
        }

        sendNormalSms(phone, properties.getTemplateCode(), content);
    }

    public AlidayuProperties getProperties() {
        return properties;
    }

    public void setProperties(AlidayuProperties properties) {
        this.properties = properties;
    }
}
